package cn.skyquant.quant4j.api.quant;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;

public class Bar implements Serializable,Cloneable {
    public static final long serialVersionUID = 1L;
    public final double open;
    public final double close;
    public final double high;
    public final double low;
    public final double volumn;

    public Bar(double open , double close, double high, double low, double volumn) {
        this.open = open;
        this.close = close;
        this.high = high;
        this.low = low;
        this.volumn = volumn;
    }

    @Override
    public String toString() {
        return String.format("open=%s,close=%s,high=%s,low=%s,volumn=%s", open, close, high, low, volumn);
    }

    public static final Bar merge(List<? extends Bar> barList){
        if(barList==null || barList.size()==0){
            return null;
        }
        if(barList.size()==1){
            return barList.get(0);
        }
        double open = barList.get(0).open;
        double close = barList.get(barList.size()-1).close;
        double high = 0;
        double low = Double.MAX_VALUE;
        double volumn = 0;
        for(Bar b:barList){
            if(b.high> high){
                high = b.high;
            }
            if(b.low < low){
                low = b.low;
            }
            volumn += b.volumn;
        }
        Bar bar = new Bar(open,close,high,low,volumn);
        return bar;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Bar)) return false;
        Bar bar = (Bar) o;
        return Double.compare(bar.open, open) == 0 &&
                Double.compare(bar.close, close) == 0 &&
                Double.compare(bar.high, high) == 0 &&
                Double.compare(bar.low, low) == 0 &&
                Double.compare(bar.volumn, volumn) == 0;
    }

    @Override
    public int hashCode() {
        return Objects.hash(open, close, high, low, volumn);
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
